/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

(function($){
    $.fn.uploadFile = function(opt){
        
        var param = {
            url        : "/",
            btnAddFile : 'upload',
            btnStart   : 'btn_start',
            autoStart  : false,
            multiSelect: false,
            aditionalParam : {},
            progress   : function(up,file){ console.log('processando...'); },
            callback   : function(up,file,obj){console.log('arquivo enviado'); },
            error      : function(up,err){console.log(err);}
        };
        opt = $.extend(param,opt);
        
        /*instacia o objeto do plugin do upload*/
        var upload = new plupload.Uploader({
            runtimes      : 'html5,flash,silverlight,html4',
            flash_swf_url : 'admin/assets/js/plupload/Moxie.swf',
            silverlight_xap_url : 'admin/assets/js/plupload/Moxie.xap',
            browse_button : opt.btnAddFile,
            url           : opt.url,
            multipart_params:opt.aditionalParam,
            filter:{
                max_file_size:"1mb",
                mime_types:[{title:"Image files", extensions:"jpg,gif,png"}]
            },
            multi_selection:opt.multiSelect
        });       
        
        /*inicializa o plugin*/
        upload.init();
        
        /*verifica o upload automatico apos a escolha do arquivo*/
        if(opt.autoStart){
            upload.bind('FilesAdded',function(up,file){
                if(opt.autoStart){ up.start();}
            });
        }else{
            jQuery(document.getElementById(opt.btnStart)).on("click",function(){
                upload.start();
            });
        } 
        
        /*pregresso*/
        upload.bind('UploadProgress',opt.progress);
        
        /*retorno*/
        upload.bind('FileUploaded',opt.callback);
        
        /*Response error*/
        upload.bind('Error',opt.error);
        
    };
})(jQuery);
